﻿using System.Collections.ObjectModel;
using System.Data;
using System.Reflection;

namespace PLCS.Shared.Common.Extensions;

public static class ListExtension
{
    /// <summary>
    /// List<string>转拼接strng
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <param name="jointchar">拼接字符</param>
    /// <returns></returns>
    public static string TojointString<T>(this List<string> list, char jointchar)
    {
        string result = "";
        for (int i = 0; i < list.Count; i++)
        {
            if (i == list.Count - 1)
            {
                result += $"{list[i]}";
                continue;
            }
            result += $"{list[i]}{jointchar}";
        }
        return result;
    }

    /// <summary>
    /// 转化一个DataTable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns></returns>
    public static DataTable ToDataTable<T>(this IEnumerable<T> list)
    {
        //创建属性的集合
        List<PropertyInfo> pList = new List<PropertyInfo>();
        //获得反射的入口
        Type type = typeof(T);
        DataTable dt = new DataTable();
        //把所有的public属性加入到集合 并添加DataTable的列
        Array.ForEach(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
        foreach (var item in list)
        {
            //创建一个DataRow实例
            DataRow row = dt.NewRow();
            //给row 赋值
            pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
            //加入到DataTable
            dt.Rows.Add(row);
        }
        return dt;
    }
}